package edu.sctu.zhengsenwen.month201506.day20150616.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import java.net.URL;

/**
 * Created by user15 on 2015/6/18.
 */
public class PostTest {


    public void httpUrlConnection() throws IOException {

        String path = null;

        try {

            URL url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);      //post请求不允许占用内存
            httpURLConnection.setRequestMethod("POST");

            String requestString = "客服端要以以流方式发送到服务端的数据...";
            byte[] requestStringToBytes = requestString.getBytes();
            httpURLConnection.setRequestProperty("Content-length", " " + requestStringToBytes.length);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");

            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(requestStringToBytes);
            outputStream.close();

            int response = httpURLConnection.getResponseCode();
            if (httpURLConnection.HTTP_OK == response) {

                BufferedReader responseReader;
                responseReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), " "));

                String readLine;
                StringBuffer stringBuffer = new StringBuffer();

                if ((readLine = responseReader.readLine()) != null) {

                    stringBuffer.append(readLine).append("\n");
                }

                responseReader.close();
                stringBuffer.toString();

            }


        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}


